import { getToken } from "share/common";
import moment from "moment/moment";
import configureStore from "stores/index";

// 某些列的默认宽度，会跟多语言挂钩
const DEFAULT_WITH_FOR_INDEX_MAP = {
  status: {
    zh_cn: 120,
    def: 200,
  },
};

export default {
  addClassName(target = "", className = "") {
    const classNameAry = target.split(/\s+/gim);
    if (!classNameAry.includes(className)) {
      classNameAry.push(className);
    }
    return classNameAry.join(" ");
  },
  removeClassName(target = "", className = "") {
    return target.replace(className, "");
  },
  getLanguageCode() {
    return configureStore.store.getState().main.language.code;
  },
  // 行数据缓存操作
  handleRecordCache({ tableName = "", record, rowKey = "id", action }) {
    if (!tableName) return tableName;
    const cacheKey = `hly.record.${tableName}.cache`;
    const id = typeof rowKey === "function" ? rowKey(record) : rowKey;
    const value = record[id] || id;
    const cachedValue = sessionStorage.getItem(cacheKey);
    if (action === "set") {
      if (value && cachedValue !== value) {
        sessionStorage.setItem(cacheKey, value);
        return true;
      }
    } else if (action === "get") {
      return cachedValue === value;
    }
    return false;
  },
  // 页码缓存处理
  handlePageCache({ tableName, page = 0 }) {
    if (!tableName) return page;
    const cacheKey = `hly.page.${tableName}.cache`;
    if (window.isBackward) {
      window.isBackward = false;
      const n = parseInt(sessionStorage.getItem(cacheKey));
      if (isNaN(n)) return 0;
      return n;
    }
    sessionStorage.setItem(cacheKey, page);
    return page;
  },
  // 清理页码缓存
  handlePageCacheRemove(tableName) {
    sessionStorage.removeItem(`hly.page.${tableName}.cache`);
  },
  // 处理缓存条件
  handleSearchedValuesCache(action = "get", { tableName, values, sourceValues, column } = {}) {
    if (!tableName) return null;
    let result = null;
    let cachedData = null;
    const cachedKey = `hly.table-${tableName}.cache`;
    if (action === "get") {
      let cachedData = sessionStorage.getItem(cachedKey);
      try {
        cachedData = JSON.parse(cachedData);
      } catch (e) {
        cachedData = null;
      }
      if (cachedData) {
        result = cachedData;
      }
      return result;
    } else if (action === "set") {
      let cachedData = {
        values,
        sourceValues,
        column,
      };
      try {
        cachedData = JSON.stringify(cachedData);
      } catch (e) {
        cachedData = null;
      }
      if (cachedData) {
        sessionStorage.setItem(cachedKey, cachedData);
        if (!sessionStorage.getItem("hly.session.token")) {
          sessionStorage.setItem("hly.session.token", JSON.parse(getToken()).access_token);
        }
      }
    } else if (action === "remove") {
      sessionStorage.removeItem(cachedKey);
    }
    return result;
  },
  // 将搜索条件中的ISO字符串转换成moment对象
  transferISOStringToDate(values = {}) {
    if (!values) return {};
    let reg = /^[0-9]{4}\-\d+-\d+T[0-9\:]+\.\d+Z$/;
    Object.keys(values).forEach((key) => {
      let value = values[key];
      if (!value) return;
      if (Array.isArray(value)) {
        values[key] = value.map((subItem) => {
          if (typeof subItem === "string" && subItem.match(reg)) {
            return moment(subItem);
          } else {
            return subItem;
          }
        });
      } else if (typeof value === "object") {
        values[key] = this.transferISOStringToDate(value);
      } else if (typeof value === "string" && value.match(reg)) {
        values[key] = moment(value);
      }
    });
    return values;
  },
  // 处理某些列的默认宽度，比如状态/金额之类的
  getDefColumnWidthByIndex(index) {
    let languageCode = this.getLanguageCode();
    const indexMap = DEFAULT_WITH_FOR_INDEX_MAP[index] || {};
    const width = indexMap[languageCode] || indexMap["def"];
    return width;
  },
};
